package com.actions.bluetoothbox2.fragment;

import android.annotation.TargetApi;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockFragment;
import com.actions.bluetoothbox2.R;
import com.actions.bluetoothbox2.app.BrowserActivity;
import com.actions.bluetoothbox2.util.DButils;
import com.actions.bluetoothbox2.util.PopupColorSelecter;
import com.actions.bluetoothbox2.util.PopupColorSelecter1;
import com.actions.bluetoothbox2.util.PopupColorSelecter2;
import com.actions.bluetoothbox2.util.PopupVoiceSelecter2;
import com.actions.bluetoothbox2.util.RoundCornerDrawable;
import com.actions.bluetoothbox2.util.Utils;
import com.actions.bluetoothbox2.util.VoiceInfo;
import com.actions.ibluz.manager.BluzManager;
import com.actions.ibluz.manager.BluzManagerData;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

public class SleepFragment extends SherlockFragment {

    private final static String TAG = "SleepFragment";
    private BrowserActivity mActivity;
    private View mView;
    //    private Switch sleep_switch;
    private Button btn_start, btn_close, sleep_color;
    //    private CircleView sleep_color_circle;
    private TextView tv__lights_time;
    private SeekBar seekbar_lights_time;
    //    private ImageView sleep_voice, sleep_rorest, sleep_wind, sleep_rain, sleep_wave, sleep_bird;
    private ImageView imageViews[] = new ImageView[8];
    private int imgs[] = new int[]{R.drawable.ic_41, R.drawable.ic_45, R.drawable.ic_42,
            R.drawable.ic_43, R.drawable.ic_44, R.drawable.ic_46, R.drawable.ic_47, R.drawable.ic_48};
    private int imgs_select[] = new int[]{R.drawable.ic_41_select, R.drawable.ic_45_select,
            R.drawable.ic_42_select, R.drawable.ic_43_select, R.drawable.ic_44_select,
            R.drawable.ic_46_select, R.drawable.ic_47_select, R.drawable.ic_48_select};

    private BluzManager mBluzManager;
    private int lights_time = 0;
    private boolean isopen;
    private PopupColorSelecter1 popupColorSelecter;
    private PopupColorSelecter2 popupColorSelecter2;
    private PopupVoiceSelecter2 popupVoiceSelecter2;
    private int cmd_type;
    private int cmd_id;
    private int ring_seq = 0;
    private int sd_seq = 0;
    private int mColor;
    private int sleepledtype = 2;
    private ImageView view_color;
    private List<VoiceInfo> list_voice;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        setHasOptionsMenu(true);
        mActivity = (BrowserActivity) getActivity();
        mView = inflater.inflate(R.layout.fragment_sleep, container, false);
        mBluzManager = mActivity.getBluzManager();
        cmd_type = Integer.decode("0x53");
        cmd_id = Integer.decode("0x95");
        mActivity.tv_title.setText(getResources().getText(R.string.sleep));
        mActivity.getSlidingMenu().setTouchModeAbove(SlidingMenu.TOUCHMODE_NONE);
        mActivity.mGlobalInfoLayout.setVisibility(View.VISIBLE);
        mActivity.title_img_right.setVisibility(View.GONE);
        initView();
        popupColorSelecter2 = new PopupColorSelecter2(getActivity());
        popupColorSelecter2.setSelected(listener2);

        popupColorSelecter = new PopupColorSelecter1(getActivity(), popupColorSelecter2, sleep_color);
        popupColorSelecter.setSelected(listener);
        mActivity.title_back.setVisibility(View.VISIBLE);

        if(mActivity.is_TF){
            list_voice = DButils.queryAll();
            if (null == list_voice || list_voice.size() == 0) {
                getVoide();
            } else {
                IsUpdata();
            }
        }
        popupVoiceSelecter2 = new PopupVoiceSelecter2(mActivity);
        popupVoiceSelecter2.setSelected(new PopupVoiceSelecter2.onSelecteListener() {
            @Override
            public void onSelected(VoiceInfo info) {
                ring_seq = 0;
                sd_seq = info.song_seq;
            }
        });
        return mView;
    }

    int imgid;
    PopupColorSelecter1.onSelecteListener listener = new PopupColorSelecter1.onSelecteListener() {
        @Override
        public void onSelected(int position, int imgID) {
            imgid = imgID;
            sleep_color.setBackgroundResource(imgID);
            if (position == 11) {
                sleepledtype = 12;
                popupColorSelecter2.showAtLocation(sleep_color, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
            } else if (position == 10) {
                sleepledtype = 1;
            } else {
                sleepledtype = position + 2;
            }
        }
    };
    PopupColorSelecter2.onSelecteListener listener2 = new PopupColorSelecter2.onSelecteListener() {
        @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
        @Override
        public void onSelected(int color) {
            sleepledtype = 12;
            mColor = color;
            imgid = 12;
            Log.i(TAG, "mColor====" + mColor);
            RoundCornerDrawable drawable = new RoundCornerDrawable(mColor, sleep_color.getWidth() / 2, sleep_color.getHeight(), sleep_color.getWidth());
            mActivity.sleep_drawable = drawable;
            sleep_color.setBackground(drawable);
        }
    };

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    private void initView() {
//        sleep_switch = (Switch) mView.findViewById(R.id.sleep_switch);
        btn_start = (Button) mView.findViewById(R.id.btn_start);
        btn_close = (Button) mView.findViewById(R.id.btn_close);
        tv__lights_time = (TextView) mView.findViewById(R.id.tv__lights_time);
        seekbar_lights_time = (SeekBar) mView.findViewById(R.id.seekbar_lights_time);

        imageViews[0] = (ImageView) mView.findViewById(R.id.sleep_rorest);
        imageViews[1] = (ImageView) mView.findViewById(R.id.sleep_bird);
        imageViews[2] = (ImageView) mView.findViewById(R.id.sleep_wind);
        imageViews[3] = (ImageView) mView.findViewById(R.id.sleep_rain);
        imageViews[4] = (ImageView) mView.findViewById(R.id.sleep_wave);
        imageViews[5] = (ImageView) mView.findViewById(R.id.sleep_night);
        imageViews[6] = (ImageView) mView.findViewById(R.id.sleep_sleep);
        imageViews[7] = (ImageView) mView.findViewById(R.id.sleep_custom);
        sleep_color = (Button) mView.findViewById(R.id.sleep_color);
        view_color = (ImageView) mView.findViewById(R.id.view_color);

        if (mActivity.sleep_time != 0) {
            seekbar_lights_time.setProgress(mActivity.sleep_time);
            tv__lights_time.setText(mActivity.sleep_time + "" + getResources().getString(R.string.snooze_minute));
            lights_time = mActivity.sleep_time;
        }

        for (int i = 0; i < imageViews.length; i++) {
            imageViews[i].setOnClickListener(onclick);
            imageViews[i].setImageResource(imgs[i]);
        }
//        imageViews[0].setImageResource(imgs_select[0]);
        ring_seq = mActivity.ring_seq;
        imageViews[mActivity.ring_seq].setImageResource(imgs_select[mActivity.ring_seq]);

        if (mActivity.sleepledtype_imgID == 15) if (mActivity.sleep_color == 0) {
            sleep_color.setBackgroundResource(R.drawable.ic_coloured);
        } else {
            mColor = mActivity.sleep_color;
//                Log.i("TAG", "sleep_color===" + mColor + "----sleepledtype_imgID===="
//                        + mActivity.sleepledtype_imgID + "--red==" + red + "--green==" + green + "-blue==" + blue);
            sleep_color.setBackground(mActivity.sleep_drawable);
        }
        else {
            if (mActivity.sleepledtype_imgID == 0) {
                sleep_color.setBackgroundResource(R.drawable.ic_coloured);
            } else {
                sleep_color.setBackgroundResource(mActivity.sleepledtype_imgID);
            }
        }


        btn_start.setOnClickListener(onclick);
        btn_close.setOnClickListener(onclick);
        sleep_color.setOnClickListener(onclick);

        seekbar_lights_time.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
                lights_time = i;
                tv__lights_time.setText(lights_time + "" + getResources().getString(R.string.snooze_minute));
//                if (isopen) {
//                    mBluzManager.sendCustomCommand(cmd_type << 8 | cmd_id, lights_time, 0, null);
//                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
    }

    View.OnClickListener onclick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.sleep_rorest:
                    selectImg((ImageView) v);
                    ((ImageView) v).setImageResource(imgs_select[0]);
                    ring_seq = 1;
                    break;
                case R.id.sleep_bird:
                    selectImg((ImageView) v);
                    ((ImageView) v).setImageResource(imgs_select[1]);
                    ring_seq = 2;
                    break;
                case R.id.sleep_wind:
                    selectImg((ImageView) v);
                    ((ImageView) v).setImageResource(imgs_select[2]);
                    ring_seq = 3;
                    break;
                case R.id.sleep_rain:
                    selectImg((ImageView) v);
                    ((ImageView) v).setImageResource(imgs_select[3]);
                    ring_seq = 4;
                    break;
                case R.id.sleep_wave:
                    selectImg((ImageView) v);
                    ((ImageView) v).setImageResource(imgs_select[4]);
                    ring_seq = 5;
                    break;
                case R.id.sleep_night:
                    selectImg((ImageView) v);
                    ((ImageView) v).setImageResource(imgs_select[5]);
                    ring_seq = 6;
                    break;
                case R.id.sleep_sleep:
                    selectImg((ImageView) v);
                    ((ImageView) v).setImageResource(imgs_select[6]);
                    ring_seq = 7;
                    break;
                case R.id.sleep_custom:
                    if(mActivity.is_TF){
                        selectImg((ImageView) v);
                        ((ImageView) v).setImageResource(imgs_select[7]);
                        ring_seq = 0;
                        popupVoiceSelecter2.showAtLocation(v, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
                    }else {
                        Toast.makeText(mActivity, "卡不存在，请选择内置铃声", Toast.LENGTH_SHORT).show();
                    }
                    break;
                case R.id.btn_start:
                    mActivity.sleep_time = lights_time;
                    mActivity.ring_seq = ring_seq;
                    mActivity.sleepledtype_imgID = imgid;
                    if (imgid == 12) {
                        mActivity.sleep_color = mColor;
                    }
                    Log.i("TAG", "mColor===" + mColor + "----imgid====" + imgid);
                    tv__lights_time.setText(lights_time + "" + getResources().getString(R.string.snooze_minute));
                    seekbar_lights_time.setProgress(lights_time);

                    mBluzManager.sendCustomCommand(cmd_type << 8 | cmd_id, sd_seq, lights_time << 16 | sleepledtype << 8 | ring_seq, null);
                    if (sleepledtype == 1 || sleepledtype == 2) {

                    } else {
                        int cmd_type = Integer.decode("0x53");
                        int cmd_id = Integer.decode("0x91");
                        int brightness = 0;
                        if (sleepledtype == 12) {
                            brightness = 0;
                            int red = (mColor & 0xff0000) >> 16;
                            int green = (mColor & 0x00ff00) >> 8;
                            int blue = (mColor & 0x0000ff);
                            isopen = true;
                            mBluzManager.sendCustomCommand(cmd_type << 8 | cmd_id, brightness << 24 | red << 16 | green << 8 | blue, 0, null);
                        } else if (sleepledtype == 3) {
                            isopen = true;
                            mBluzManager.sendCustomCommand(cmd_type << 8 | cmd_id, 0xFFFFFF, 0, null);
                        } else if (sleepledtype == 4) {
                            isopen = true;
                            mBluzManager.sendCustomCommand(cmd_type << 8 | cmd_id, 0xFF0F05, 0, null);
                        } else if (sleepledtype == 5) {
                            isopen = true;
                            mBluzManager.sendCustomCommand(cmd_type << 8 | cmd_id, 0xFF5700, 0, null);
                        } else if (sleepledtype == 6) {
                            isopen = true;
                            mBluzManager.sendCustomCommand(cmd_type << 8 | cmd_id, 0xFF8F00, 0, null);
                        } else if (sleepledtype == 7) {
                            isopen = true;
                            mBluzManager.sendCustomCommand(cmd_type << 8 | cmd_id, 0x55D640, 0, null);
                        } else if (sleepledtype == 8) {
                            isopen = true;
                            mBluzManager.sendCustomCommand(cmd_type << 8 | cmd_id, 0x5CD1FF, 0, null);
                        } else if (sleepledtype == 9) {
                            isopen = true;
                            mBluzManager.sendCustomCommand(cmd_type << 8 | cmd_id, 0x1D10E5, 0, null);
                        } else if (sleepledtype == 10) {
                            isopen = true;
                            mBluzManager.sendCustomCommand(cmd_type << 8 | cmd_id, 0xD100F9, 0, null);
                        } else if (sleepledtype == 11) {
                            isopen = true;
                            mBluzManager.sendCustomCommand(cmd_type << 8 | cmd_id, 0xFF0D85, 0, null);
                        }
                    }

                    break;
                case R.id.btn_close:
                    tv__lights_time.setText(R.string.off);
                    seekbar_lights_time.setProgress(0);
                    isopen = false;
                    mBluzManager.sendCustomCommand(cmd_type << 8 | cmd_id, 0, 0, null);
                    break;
                case R.id.sleep_color:
                    popupColorSelecter.showAtLocation(v, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
                    break;
                default:
                    break;
            }
        }
    };

    private void selectImg(ImageView img) {
        for (int i = 0; i < imageViews.length; i++) {
            imageViews[i].setImageResource(imgs[i]);
        }
    }

    private void IsUpdata() {
        mBluzManager.setOnCustomCommandListener(new BluzManagerData.OnCustomCommandListener() {

            @Override
            public void onReady(int i, int i1, int i2, byte[] bytes) {
                int type = Utils.bytesToInt(bytes, 0);
                Log.i("TAG", "onReady: ----type == " + type);
                if (i1 == 1 && type == 1) {
                    getVoide();
                } else {
                    popupVoiceSelecter2.setList_voice(list_voice);
                }
            }
        });
        int cmd_type = Integer.decode("0x51");
        int cmd_id = Integer.decode("0x81");
        mBluzManager.sendCustomCommand(cmd_type << 8 | cmd_id, 1, 0, null);
    }

    public void getVoide() {
        mBluzManager.setOnCustomCommandListener(new BluzManagerData.OnCustomCommandListener() {
            @Override
            public void onReady(int i, int i1, int i2, byte[] bytes) {

                DButils.deleteLove();
                List<VoiceInfo> infos_music = new ArrayList<>();
                List<Byte> list_byte = new ArrayList<>();
                for (int j = 0; j < bytes.length; j++) {
                    list_byte.add(bytes[j]);
                }
                int count = bytes.length / 64;
                for (int j = 0; j < count; j++) {
                    List<Byte> byet_list = list_byte.subList(j * 64, 64 * (j + 1));

                    VoiceInfo info = new VoiceInfo();
                    info.ring_type = byet_list.get(0);

                    byte[] b1 = new byte[4];
                    b1[0] = byet_list.get(1);
                    b1[1] = byet_list.get(2);
                    b1[2] = 0;
                    b1[3] = 0;
                    info.song_seq = Utils.bytesToInt(b1, 0);

                    info.code_type = byet_list.get(3);

                    byte b2[] = new byte[60];
                    for (int l = 0; l < 60; l++) {
                        b2[l] = byet_list.get(l + 4);
                    }
                    info.song_name_b = b2;
                    try {
                        int coun = Utils.getVirtualValueLength(b2, info.ring_type);
                        byte[] b3 = new byte[coun];
                        for (int k = 0; k < coun; k++) {
                            b3[k] = b2[k];
                        }
                        switch (info.ring_type) {
                            case 0:
                                info.song_name = new String(b3, "GBK");
                                break;
                            case 1:
                                info.song_name = new String(b3, "UTF-16LE");
                                break;
                            case 2:
                                info.song_name = new String(b3, "UTF-16BE");
                                break;
                            case 3:
                                info.song_name = new String(b3, "UTF-8");
                                break;
                            default:
                                break;
                        }
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                    DButils.insertCart(info);
                    infos_music.add(info);
                }
                popupVoiceSelecter2.setList_voice(infos_music);
            }
        });
        int cmd_type = Integer.decode("0x51");
        int cmd_id = Integer.decode("0x99");
        mBluzManager.sendCustomCommand(cmd_type << 8 | cmd_id, 0, 0, null);
    }
}
